package top.syfy.jwt.jwtdemo.sysmag.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.syfy.jwt.jwtdemo.bean.UserBean;
import top.syfy.jwt.jwtdemo.exception.CustomerException;
import top.syfy.jwt.jwtdemo.jwt.JwtProvide;
import top.syfy.jwt.jwtdemo.message.CodeEnum;
import top.syfy.jwt.jwtdemo.message.ReturnMessage;
import top.syfy.jwt.jwtdemo.message.ReturnMessageUtil;
import top.syfy.jwt.jwtdemo.redis.RedisProvide;
import top.syfy.jwt.jwtdemo.util.Object2MapUtil;
import top.syfy.jwt.jwtdemo.util.TokenUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

/**
 * 完成用户的登录与注销登录
 *
 * @author syfy
 * @date 2021/03/07
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping(value = "/sys")
public class SystemController {

	private static final Logger logger = LoggerFactory.getLogger(SystemController.class);

	@Autowired
	private RedisProvide redisProvide;

	@Autowired
	private JwtProvide jwtProvide;

	/**
	 * 用户登录
	 *
	 * @param loginName 登录名
	 * @param password  密码
	 * @param session   HTTP会话
	 * @return 返回消息对象(用户登录操作结果)
	 */
	@PostMapping("/login")
	public ReturnMessage<Object> login(String loginName, String password, HttpSession session) {
		/* 从数据库中根据登录名和密码查询是否存在匹配的用户数据 */
		UserBean userBean = simulationDB(loginName, password);
		if (Objects.isNull(userBean)) {
			return ReturnMessageUtil.error(CodeEnum.LOGINNAME_OR_PASSWD_ERROR);
		}
		/* 将JavaBean实例转为Map类型的数据, 方便向JWT中追加数据 */
		Map<String, Object> userInfoClaim = null;
		try {
			userInfoClaim = Object2MapUtil.bean2Map(userBean);
		} catch (IllegalAccessException e) {
			logger.error("login() - {}", e);
			throw new CustomerException(CodeEnum.DATA_PARSE_ERROR);
		}
		/* 转换成功之后, 使用JWT令牌提供类 */
		String token = jwtProvide.createToken(userInfoClaim);
		/* 将生成的token存入Redis中 */
		redisProvide.set(token, userBean, 60 * 60 * 1L);
		//logger.info("Authorization:" + token);
		return ReturnMessageUtil.success(token);
	}

	/**
	 * 用户注销登录
	 *
	 * @param token 令牌
	 * @return 返回消息对象(注销操作结果)
	 */
	@PostMapping(value = "/logout")
	public ReturnMessage<?> logout(HttpServletRequest request) {
		/* 从Redis中清理令牌信息 */
		redisProvide.del(TokenUtil.getTokenFromReqHeader(request));
		return ReturnMessageUtil.success();
	}

	/**
	 * 模拟从数据库中查询用户信息
	 *
	 * @param loginName 登录名
	 * @param password  密码
	 * @return null或者从数据库查询得到的用户信息
	 */
	private UserBean simulationDB(String loginName, String password) {
		if (Objects.equals("admin", loginName) && Objects.equals("123456", password)) {
			UserBean u = new UserBean();
			u.setId(1L);
			u.setUserName("zs");
			u.setLoginName("zs");
			u.setPassword("123456");
			u.setAge(20);
			return u;
		}
		return null;
	}


}
